import { DynamicModule, Inject, Module, OnModuleInit } from '@nestjs/common';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { HttpAdapterHost } from '@nestjs/core';

const CUSTOM_CORS_OPTIONS = 'CUSTOM_CORS_OPTIONS';

@Module({})
export class CorsModule implements OnModuleInit {
    constructor(
        @Inject(CUSTOM_CORS_OPTIONS)
        private readonly options: CorsOptions,
        private readonly httpAdapter: HttpAdapterHost
    ) {}

    public static forRoot(options: CorsOptions): DynamicModule {
        return {
            module: CorsModule,
            providers: [
                {
                    provide: CUSTOM_CORS_OPTIONS,
                    useValue: options,
                },
            ],
        };
    }

    onModuleInit() {
        this.httpAdapter.httpAdapter.enableCors(this.options);
    }
}
